package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticelContentMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.article.pojo.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private ApArticelContentMapper contentMapper ;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService ;

    @Autowired
    private ApArticleService apArticleService ;

    //让该方法异步调用
    @Async //需要在启动类上开启异步调用
    @Override
    public void buildArticleToMinio(ApArticle article, String content) {

        if (StringUtils.isNotColumnName(content)){
            try {

                StringWriter out = new StringWriter();

                //2 生成静态文件
                Template template = configuration.getTemplate("article.ftl");
                //模板设置参数 参数1为数据，参数2 为模板对象
                Map<String,Object> map = new HashMap<>();
                //parse得到的是一个JSONArray 对象，但是给到前端页面页面可以识别，应该是因为前端页面使用了vue的原因
                map.put("content" ,  JSONArray.parseArray(content));//content内容是字符串类型的json数组，转为对象
                //把生成后的文件写入out
                template.process(map , out);

                //模板上传到minio
                ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8));
                String static_path = fileStorageService.uploadHtmlFile("", article.getId()+".html", in );
                System.out.println("文件访问地址："+static_path);

                //访问地址保存到数据库
                apArticleService.update(Wrappers.<ApArticle>lambdaUpdate()
                        .eq(ApArticle::getId , article.getId())
                        .set(ApArticle::getStaticUrl , static_path));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }





    }

}
